package com.ssm.common.config;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;

/**
 * Author:      Dante Lee
 * Time:        2015-11-05 09:59 AM
 * Description: 配置文件读写工具
 */
public class ConfigManager {

	private static ConfigManager configManager = null;
	private Properties properties = null;
	private String fileName = null;

	public ConfigManager(String file_name) {
		this.fileName = file_name;
		try {
			InputStream in = getClass().getResourceAsStream(file_name);
			properties = new Properties();
			properties.load(in);
			if (in != null)
				in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置配置文件关键字属性
	 * @param parameterKey
	 * @param parameterValue
	 * @throws IOException
	 */
	public void setProperties(String key, String value) throws IOException {
		try {
			URL url = getClass().getResource(fileName);
			String file_path = url.getPath().toString();
			OutputStream fos = new FileOutputStream(file_path);
			properties.setProperty(key, value);
			properties.store(fos, key);
			if (fos != null)
				fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置配置文件关键字属性
	 * @param parameterKey
	 * @param parameterValue
	 * @param parameterfileName
	 * @throws IOException
	 */
	public void setProperties(String key, String value, String file_name) throws IOException {
		try {
			URL url = getClass().getResource(file_name);
			String file_path = url.getPath().toString();
			OutputStream fos = new FileOutputStream(file_path);
			properties.setProperty(key, value);
			properties.store(fos, key);
			if (fos != null)
				fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 得到实例化对象
	 * @return
	 */
	public static ConfigManager getInstance(String file_path) {
		configManager = new ConfigManager(file_path);
		return configManager;
	}

	/**
	 * @return 返回 properties。
	 */
	public Properties getProperties() {
		return properties;
	}

}
